package com.faintlight.service.impl;

import com.faintlight.model.Capsule;
import com.faintlight.model.User;
import com.faintlight.repository.CapsuleRepository;
import com.faintlight.repository.UserRepository;
import com.faintlight.service.UserService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserRepository userRepository;
    private final CapsuleRepository capsuleRepository;

    @Override
    @Transactional
    public User getOrCreateUser(String openId, String nickname, String avatarUrl) {
        logger.info("👤 查找或创建用户: OpenId={}", openId);
        return userRepository.findByOpenId(openId)
                .orElseGet(() -> {
                    logger.info("🆕 创建新用户: 昵称={}, 头像={}", nickname, avatarUrl);
                    User user = new User();
                    user.setOpenId(openId);
                    user.setNickname(nickname);
                    user.setAvatarUrl(avatarUrl);
                    return userRepository.save(user);
                });
    }

    @Override
    public User getUserById(Long userId) {
        logger.info("🔍 查询用户 ID={}", userId);
        return userRepository.findById(userId)
                .orElseThrow(() -> {
                    logger.error("❌ 用户不存在: ID={}", userId);
                    return new RuntimeException("用户不存在");
                });
    }

    @Override
    public int getUserTemperature(Long userId) {
        List<Capsule> unlocked = capsuleRepository.findByCreatedBy_IdAndStatus(userId, Capsule.Status.UNLOCKED);
        int sum = unlocked.stream()
                .mapToInt(capsule -> capsule.getTemperature() == null ? 0 : capsule.getTemperature())
                .sum();
        logger.debug("🌡️ 用户ID={}温度总和={}", userId, sum);
        return sum;
    }

    @Override
    public LocalDateTime getUserLastActive(Long userId) {
        List<Capsule> capsules = capsuleRepository.findByCreatedBy_Id(userId);
        LocalDateTime last = null;
        for (Capsule c : capsules) {
            if (last == null || (c.getUnlockTime() != null && c.getUnlockTime().isAfter(last))) {
                last = c.getUnlockTime();
            }
            if (c.getCreatedAt() != null && c.getCreatedAt().isAfter(last != null ? last : c.getCreatedAt().minusSeconds(1))) {
                last = c.getCreatedAt();
            }
        }
        logger.debug("🕒 用户ID={}最后活跃时间={}", userId, last);
        return last;
    }
}